package com.ctrip.utils;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import lombok.extern.slf4j.Slf4j;

/**
 * @see <a href="https://sourceforge.net/projects/jacob-project/files/jacob-project/">jacob下载地址</a>
 */
@Slf4j
public class Jacob4TTS {
    private static ActiveXComponent sap;
    private static Dispatch sapo;

    private static void init() {
        if (sap == null) {
            sap = new ActiveXComponent("Sapi.SpVoice");
            sapo = sap.getObject();
        }
    }

    public static void speak(String msg) {
        try {
            init();
            // 音量 0-100
            sap.setProperty("Volume", new Variant(100));
            // 语音朗读速度 -10 到 +10
            sap.setProperty("Rate", new Variant(0));
            // 执行朗读
            log.info("speak:{}", msg);
            Dispatch.call(sapo, "Speak", new Variant(msg));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void release() {
        if (sap != null) {
            sapo.safeRelease();
            sap.safeRelease();
            sapo = null;
            sap = null;
        }
    }
}
